package com.ajie.config.security.service;

import com.ajie.entity.SysMenu;
import com.ajie.entity.SysUser;
import com.ajie.mapper.SysMiniUserMapper;
import com.ajie.mapper.SysUserMapper;
import com.ajie.utils.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 实现用户UserDetailsService自定义登录接口逻辑
 * 从写loadUserByUsername方法
 */
@Service
@Slf4j
public class UserDetailServiceImpl implements UserDetailsService {

    @Autowired
    private SysUserMapper userMapper;
    
    @Autowired
    private SysMiniUserMapper miniUserMapper;

    @Autowired
    private RedisUtil redisUtil;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //1.在mapper中自定义登录，根据用户名获取用户信息
        SysUser user ;
        log.info("该文件名是：UserDetailServiceImpl,该方法是：loadUserByUsername");
        log.info("loadUserByUsername-->在mapper中自定义登录，根据用户名获取用户信息");
        if (redisUtil.haskey("userInfo_" + username)){
            //缓存中存在用户信息、直接从redis中取
            log.info("UserDetails-->缓存中存在用户信息、直接从redis中取");
            user = (SysUser) redisUtil.getValue("userInfo_" + username);
            redisUtil.expire("userInfo_" + username , 5);
        }else {
            log.info("UserDetails-->redis缓存中没有用户信息，需要存数据库中查询 username -->{}",username);
            user = userMapper.findByUserName(username);
            log.info("查询到的数据结果为-->{}",user);
            if (null == user){
             
             throw new UsernameNotFoundException("用户不存在::"+username);
//                 miniUserMapper.insertOpenId(username);
//                 SysUser user1 = userMapper.findByUserName(username);
//                 return user1;
            }
                //非管理员需要查询角色信息
                user.setRoles(userMapper.findRoles(user.getId()));
                user.setPermissions(userMapper.findPermissions(user.getId()));
                //获取父级菜单
                List<SysMenu> menus = userMapper.findMenus(user.getId());
                //获取自己菜单
                menus.forEach((item)-> item.setChildren(userMapper.findChildrenMenus(item.getId(), user.getId())));
                user.setMenus(menus);
            //}
            log.info("将用户信息存入redis中");
            redisUtil.setValueTime("userInfo_" + username, user,5);
        }
        return user;
    }
}
